package com.punch.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.punch.common.constant.CommonConstant;
import com.punch.common.dto.login.AppLoginUserDTO;
import com.punch.common.dto.user.user.PlatformUserDTO;
import com.punch.common.dto.user.user.RedisUserDTO;
import com.punch.common.exception.BusinessException;
import com.punch.common.model.LoginUser;
import com.punch.common.simple.redis.utils.RedisUtil;
import com.punch.common.simple.redis.utils.UserUtil;
import com.punch.common.vo.user.user.PlatformUserVO;
import com.punch.user.exception.UserExceptionEnum;
import com.punch.user.mapper.PlatformUserMapper;
import com.punch.user.model.PlatformUser;
import com.punch.user.service.PlatformUserService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Optional;

/**
 * <p>
 * 平台用户 服务实现类
 * </p>
 *
 * @author wjj
 * @since 2020-12-03
 */
@Service
public class PlatformUserServiceImpl extends ServiceImpl<PlatformUserMapper, PlatformUser> implements PlatformUserService {

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private PasswordEncoder passwordEncoder;


    /**
     * 平台用户登录,不存在则注册
     *
     * @param appLoginUserDTO 平台用户表单
     */
    @Override
    public void saveOrUpdatePlatformUser(AppLoginUserDTO appLoginUserDTO) {
        QueryWrapper<PlatformUser> queryWrapper = new QueryWrapper<>();
        //根据openId获取家长信息
        queryWrapper.lambda().eq(PlatformUser::getMobile, appLoginUserDTO.getMobile());
        PlatformUser platformUserEX = getOne(queryWrapper);
        //密码登录的没有则抛出异常
        if (StrUtil.isNotEmpty(appLoginUserDTO.getPassword())) {
            Optional.ofNullable(platformUserEX).orElseThrow(() -> new BusinessException(UserExceptionEnum.USER_NOT_EXIST));
            PlatformUser platformUser = new PlatformUser();
            platformUser.setId(platformUserEX.getId());
            setAppDeviceInfo(platformUser, appLoginUserDTO);
            updateById(platformUser);
        }
        //验证码登录的
        if (StrUtil.isNotEmpty(appLoginUserDTO.getCode())) {
            //不存在则注册
            if (platformUserEX == null) {
                PlatformUser platformUser = new PlatformUser();
                platformUser.setMobile(appLoginUserDTO.getMobile());
                setAppDeviceInfo(platformUser, appLoginUserDTO);
                //随机生成用户昵称
                String randomChar = StrUtil.sub(IdUtil.fastSimpleUUID(), 0, 8).toUpperCase();
                platformUser.setNickName("爱学坊-" + randomChar);
                save(platformUser);
            } else {
                PlatformUser platformUser = new PlatformUser();
                platformUser.setId(platformUserEX.getId());
                setAppDeviceInfo(platformUser, appLoginUserDTO);
                updateById(platformUser);
            }
        }

    }

    /**
     * 获取用户信息
     *
     * @param mobile 手机号码
     * @return LoginUser
     */
    @Override
    public LoginUser getUserByMobile(String mobile) {
        QueryWrapper<PlatformUser> queryWrapper = new QueryWrapper<>();
        //根据手机号码查找
        queryWrapper.lambda().eq(PlatformUser::getMobile, mobile);
        PlatformUser platformUser = getOne(queryWrapper);
        Optional.ofNullable(platformUser).orElseThrow(() -> new BusinessException(UserExceptionEnum.USER_NOT_EXIST));
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(platformUser.getId());
        loginUser.setPassword(platformUser.getPassword());
        loginUser.setEnabled(platformUser.getEnabled() == 1);
        //用户信息存放redis中
        StringBuilder sb = new StringBuilder();
        sb.append(CommonConstant.SECURITY_REDIS_USER_PREFIX).append("app:").append(platformUser.getId());
        RedisUserDTO redisUserDTO = new RedisUserDTO();
        redisUserDTO.setUserId(platformUser.getId());
        redisUtil.setValue(sb.toString(), redisUserDTO, 28800L);
        return loginUser;
    }

    /**
     * 平台用户忘记密码
     *
     * @param appLoginUserDTO 平台用户表单
     */
    @Override
    public Boolean forgetUserPwd(AppLoginUserDTO appLoginUserDTO) {
        QueryWrapper<PlatformUser> queryWrapper = new QueryWrapper<>();
        //根据手机号码查找
        String mobile = appLoginUserDTO.getMobile();
        queryWrapper.lambda().eq(PlatformUser::getMobile, mobile);
        PlatformUser platformUserEX = getOne(queryWrapper);
        //不存在则注册
        if (platformUserEX == null) {
            PlatformUser platformUser = new PlatformUser();
            setAppDeviceInfo(platformUser, appLoginUserDTO);
            platformUser.setMobile(mobile);
            //随机生成用户昵称
            String randomChar = StrUtil.sub(IdUtil.fastSimpleUUID(), 0, 8).toUpperCase();
            platformUser.setNickName("爱学坊-" + randomChar);
            platformUser.setPassword(passwordEncoder.encode(appLoginUserDTO.getPassword()));
            save(platformUser);
        } else {
            PlatformUser platformUser = new PlatformUser();
            platformUser.setId(platformUserEX.getId());
            setAppDeviceInfo(platformUser, appLoginUserDTO);
            platformUser.setPassword(passwordEncoder.encode(appLoginUserDTO.getPassword()));
            updateById(platformUser);
        }
        return true;
    }

    /**
     * 获取app登录用户信息
     *
     * @return PlatformUserVO
     */
    @Override
    public PlatformUserVO getLoginUser() {
        Long userId = UserUtil.getLoginUserId();
        PlatformUser platformUser = getById(userId);
        Optional.ofNullable(platformUser).orElseThrow(() -> new BusinessException(UserExceptionEnum.USER_NOT_EXIST));
        PlatformUserVO platformUserVO = new PlatformUserVO();
        BeanUtil.copyProperties(platformUser, platformUserVO);
//        String desensitizationMobile = platformUser.getMobile().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
//        platformUserVO.setMobile(desensitizationMobile);
        //获取未付款订单数量
        platformUserVO.setUnPayCount(2);
        return platformUserVO;
    }

    /**
     * 修改app用户信息
     *
     * @param platformUserDTO 用户修改表单
     */
    @Override
    public void updatePlatformUser(PlatformUserDTO platformUserDTO) {
        Long userId = UserUtil.getLoginUserId();
        PlatformUser platformUserEX = getById(userId);
        Optional.ofNullable(platformUserEX).orElseThrow(() -> new BusinessException(UserExceptionEnum.USER_NOT_EXIST));
        PlatformUser platformUser = new PlatformUser();
        BeanUtil.copyProperties(platformUserDTO, platformUser);
        platformUser.setId(userId);
        updateById(platformUser);
    }


    /**
     * 设置设备信息
     *
     * @param platformUser    平台用户表
     * @param appLoginUserDTO 登录信息
     */
    private void setAppDeviceInfo(PlatformUser platformUser, AppLoginUserDTO appLoginUserDTO) {
        platformUser.setLastLoginTime(LocalDateTime.now());
        //设备信息
        platformUser.setOs(appLoginUserDTO.getOs());
        platformUser.setOsVersion(appLoginUserDTO.getOsVersion());
        platformUser.setDeviceId(appLoginUserDTO.getDeviceId());
        platformUser.setDeviceType(appLoginUserDTO.getDeviceType());
        platformUser.setAppVersion(appLoginUserDTO.getAppVersion());
    }

}
